﻿using System;
using System.Net.Mail;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;



/// <summary>
/// 包含常用的系统功能
/// </summary>
public static class Utilities
{
    static Utilities()
    {
        //
        // TODO: Add constructor logic here
        //
    }

    public static bool DatabaseBackup(string connectionString, string path, string bakName)
    {
        SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(connectionString);
        string database = builder.InitialCatalog;
        string sql = "backup database "+ database + " to disk = '" + path
                + bakName  
                + System.DateTime.Now.DayOfYear.ToString()
                + System.DateTime.Now.Millisecond.ToString() + ".bak'";
        SqlConnection conn = new SqlConnection(connectionString);
        SqlCommand cmd = new SqlCommand(sql, conn);
        try
        {
            conn.Open();
            cmd.ExecuteNonQuery();
            return true;
        }
        catch (Exception ex)
        {
            return false;
            throw ex;
        }
        finally
        {
            conn.Close();
        }

    }

    public static bool DatabaseRestore(string connectionString, string path, string bakName)
    {
        SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(connectionString);
        string database = builder.InitialCatalog;
        string sql = "Alter Database "+database+" Set Offline with Rollback immediate;"; //db 是要备份的数据库名
        sql += "restore database " + database + " from disk = '";
        sql += path;
        sql += bakName + "'";  //bakname 是备份文件名
        sql += "Alter Database " + database + " Set OnLine With rollback Immediate;";
        builder.InitialCatalog = "master";
        SqlConnection conn = new SqlConnection(builder.ConnectionString);
        SqlCommand cmd = new SqlCommand(sql, conn);
        try
        {
            conn.Open();
            cmd.ExecuteNonQuery();
            return true;
        }
        catch (Exception ex)
        {
            return false;
            throw ex;
        }
        finally
        {
            conn.Close();
        }
    }
}
